<template>
	<div class="body-content">
		<div class="phot-passive-device">
			<div class="phot-passive-device-toolbar">
				<div class="toolbar-content">
					<pui-toolbar :toolbarList="hooksData.passiveDeviceToolbarList" @onInputHandle="onInputHandle"></pui-toolbar>
				</div>
			</div>
			<div class="phot-passive-device-main">
				<div class="left">
					<DeviceContent ref="DeviceContentRef" />
				</div>
				<div class="center">
                    <pui-tabs ref="tabsRef" :tabList="mainRef.gridList" @onRemove="removeTab" @onAdd="addTab"
                        @onClickHandle="tabClickHandle" add remove></pui-tabs>
                    <div class="preview-content">
                        <div class="preview-list" v-for="(item, i) in mainRef.gridList" :key="i" v-show="mainRef.gridList.length > 0 && mainRef.nowGridId === item.id">
							<ViewContent :ref="`FiguresViewRef-${item.id}`"></ViewContent>
                        </div>
						<div class="content-null" v-show="mainRef.gridList.length === 0">
							<div class="img">
								<img draggable="false" src="@/assets/logo_4.png" />
							</div>
							<div class="btn-list">
								<pui-button type="primary" @click="addTab">新建工程</pui-button>
								<pui-button @click="openFolderBrowser">打开工程</pui-button>
							</div>
						</div>
                    </div>
                    <!--<MessageLog ref="MessageLogRef" />-->
				</div>
				<div class="right">
					<CompoHistory ref="CompoHistoryRef" />
				</div>
			</div>
		</div>
		<NewPassiveDeviceDialog ref="NewPassiveDeviceDialogRef" @openFolderBrowser="openFolderBrowser" :directoryPath="mainRef.directoryPath" @onClose="mainRef.directoryPath = './photlab'" @sendGridData="getGridData"  />
		<FolderBrowserDialog ref="FolderBrowserDialogRef" @onSubmit="onFolderSubmit" :root="mainRef.directoryPath"/>
		<TaskManagementDialog ref="TaskManagementDialogRef"/>
		<MaterialManagerDialog ref="MaterialManagerDialogRef"/>
		<AddMaterialDialog ref="AddMaterialDialogRef"/>
		<EmulationAreaDialog ref="EmulationAreaRef"/>
		<SchcemaParserDialog ref="SchcemaParserDialogRef"/>
		<DirectionDialog ref="DirectionDialogRef" @changeFigure="changeFigure"/>
		<ConfirmDialog ref="ConfirmDialogRef" tip="是否确定关闭此仿真项目？" @onClose="onConfirmClose" @onSubmit="onConfirmSubmit"/>
	</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
	name: 'OptiPassiveDeviceContent'
})
</script>
<script lang="ts" setup>
import useHooks from '@/hooks'
import mainData from './index'
import { reactive, ref, onMounted, onUnmounted, getCurrentInstance, nextTick } from 'vue'
import { deviceManager } from '@/services/phot_client/device'
import { PhotGrid, PhotSource } from '@/common/types/phot_types'
import { deepClone } from '@/utils'
import MessageLog from '../explorers/message/MessageLog.vue'
import DeviceContent from './device_manager/DeviceContent.vue'
import ViewContent from './center/ViewContent.vue'
import CompoHistory from './CompoHistory.vue'
import NewPassiveDeviceDialog from './NewPassiveDevice.vue'
import FolderBrowserDialog from '../fileControl/folderBrowser.vue'
import TaskManagementDialog from '@/components/common/TaskManagement.vue'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
import MaterialManagerDialog from './MaterialManager.vue'
import AddMaterialDialog from './AddMaterial.vue'
import SchcemaParserDialog from './SchcemaParser.vue'
import EmulationAreaDialog from './EmulationArea.vue'
import DirectionDialog from './ZDirection.vue'
import { useStore } from 'vuex';
import upath from 'upath'
const store = useStore()
const { proxy } = getCurrentInstance() as any
const {
	temporaryData,
	hooksData,
	onInputHandle,
	gridData
} = useHooks()
const mainRef = reactive(mainData.mainRef)
const openFolderBrowser = async (e?: any) => {
    mainRef.directoryPath = './photlab'
    await nextTick()
    proxy.$refs.FolderBrowserDialogRef.init(e)
}
const onFolderSubmit = async (e: any) => {
    // console.log(e)
    try {
        mainRef.directoryPath = upath.normalizeSafe(e.path)
        // GRID
        if (e.file.type === 4) {
            proxy.$loading.open()
            // console.log(mainRef.directoryPath)
            await deviceManager.openGrid(mainRef.directoryPath)
			temporaryData.photGrid = deepClone(deviceManager.photGrid)
            const gridName = deviceManager.photGrid.name
            const gridId = deviceManager.photGridId
            const grid = deviceManager.photGrid
            await nextTick()
			const gridData = {
				gridId,
				name: gridName,
				grid
			}
			// proxy.$refs.CompoHistoryRef.addHistory(treeData, '1')
			await getGridData(gridData)
        	mainRef.directoryPath = './photlab'
            proxy.$loading.close()
        }
    } catch (error: any) {
        console.log(error)
        proxy.$toast({
            value: error.code === 800 ? '仿真工程已在队列' : '系统错误，请稍后重试',
            type: 'error'
        })
        proxy.$loading.close()
    }
}
// const treeData = {
// 				label:gridName,
// 				value: gridId,
// 				id: gridId,
// 				children: []
// 			}
// 			mainRef.gridList.push({
// 				name: gridName || '仿真网络',
// 				id: gridId,
// 				grid,
// 				index: mainRef.gridList.length
// 			})
// 			mainRef.nowGridId = gridId
// 			// proxy.$refs.CompoHistoryRef.addHistory(treeData, '1')
// 			mainRef.gridHistoryList.set(gridId, treeData)
// 			proxy.$refs.CompoHistoryRef.init(mainRef.gridHistoryList)
//             proxy.$loading.close()
const getGridData = async (e: any) => {
	const gridName = e.name
	const gridId = e.gridId
	const grid = e.grid
	await nextTick()
	const treeData = {
		label:gridName,
		value: gridId,
		id: gridId,
		children: []
	}
	mainRef.gridList.push({
		name: gridName || '仿真网络',
		id: gridId,
		grid,
		index: mainRef.gridList.length
	})
	hooksData.passiveDeviceToolbarList[1].options.map((option: any) => {
		option.list.map((item: any) => {
			item.readonly = false
			item.value = deviceManager.photGrid[item.prop]
		})
	})
	const compoParameters = {
		light: {},
		waveguide: {},
		detector: {}
	}
	mainRef.nowGridId = gridId
	await nextTick()
	proxy.$refs.tabsRef.updateCurrentIndex()
	mainRef.directoryPath = './'
	// proxy.$refs.CompoHistoryRef.addHistory(treeData, '1')
	mainRef.gridHistoryList.set(gridId, treeData)
	mainRef.compoParametersList.set(gridId, compoParameters)
	proxy.$refs.CompoHistoryRef.init(mainRef.gridHistoryList)
	proxy.$refs.DeviceContentRef.init()
	proxy.$refs[`FiguresViewRef-${gridId}`][0].init()
	store.dispatch('setPhotGrid', deviceManager.photGrid)
}
const removeTab = async (e: any) => {
	console.log(e)
	// await deviceManager.saveGrid(e.id)
	await deviceManager.closeGrid(e.id)
	mainRef.gridHistoryList.delete(e.id)
	if (mainRef.gridList.length > 1) {
		let nowIdx = e.index
		mainRef.nowGridId = mainRef.gridList[mainRef.gridList.length === nowIdx ? nowIdx - 1 : nowIdx].id
		await deviceManager.switchGrid(mainRef.nowGridId)
		temporaryData.photGrid = deepClone(deviceManager.photGrid)
		hooksData.passiveDeviceToolbarList[1].options.map((option: any) => {
			console.log(option)
			option.list.map((item: any) => {
				item.readonly = false
				item.value = deviceManager.photGrid[item.prop]
			})
		})
		store.dispatch('setPhotGrid', deviceManager.photGrid)
	} else {
		mainRef.nowGridId = ''
		hooksData.passiveDeviceToolbarList[1].options.map((option: any) => {
			option.list.map((item: any) => {
				item.readonly = true
				item.value = '0'
			})
		})
		store.dispatch('setPhotGrid', {})
	}
	proxy.$refs.DeviceContentRef.init()
	proxy.$refs.CompoHistoryRef.init(mainRef.gridHistoryList)
}
const addTab = async (e: any) => {
	proxy.$refs.NewPassiveDeviceDialogRef.init()
}
const tabClickHandle = async (e: any) => {
	// console.log(__dirname)
	if (e.id === deviceManager.photGridId) return
	await deviceManager.switchGrid(e.id)
	temporaryData.photGrid = deepClone(deviceManager.photGrid)
	await nextTick()
	hooksData.passiveDeviceToolbarList[1].options.map((option: any) => {
		option.list.map((item: any) => {
			if (item.prop && deviceManager.photGrid) {
			item.readonly = false
				item.value = deviceManager.photGrid[item.prop]
			}
		})
	})
	mainRef.nowGridId = e.id
	proxy.$refs.CompoHistoryRef.init(mainRef.gridHistoryList)
	proxy.$refs.DeviceContentRef.init()
	store.dispatch('setPhotGrid', deviceManager.photGrid)
}
const onConfirmClose = () => {}
const onConfirmSubmit = async () => {
	if (mainRef.gridList.length === 0) {
		proxy.$toast({
			value: '未检测到正在运行的仿真工程',
			type: 'error'
		})
		return
	}
	try {
		proxy.$loading.open('正在关闭...')
		const currentGrid = mainRef.gridList.filter((item: any) => item.id === deviceManager.photGridId)[0]
		let nowIdx = currentGrid.index
		if (mainRef.gridList.length > 1) {
			mainRef.nowGridId = mainRef.gridList[mainRef.gridList.length === nowIdx ? nowIdx - 1 : nowIdx].id
			await deviceManager.closeGrid(currentGrid.id)
			mainRef.gridHistoryList.delete(currentGrid.id)
			await deviceManager.switchGrid(mainRef.nowGridId)
			temporaryData.photGrid = deepClone(deviceManager.photGrid)
			hooksData.passiveDeviceToolbarList[1].options.map((option: any) => {
				console.log(option)
				option.list.map((item: any) => {
					item.readonly = false
					item.value = deviceManager.photGrid[item.prop]
				})
			})
			store.dispatch('setPhotGrid', deviceManager.photGrid)
		} 
		if (mainRef.gridList.length === 1) {
			await deviceManager.closeGrid(currentGrid.id)
			mainRef.gridHistoryList.delete(currentGrid.id)
			mainRef.nowGridId = ''
			mainRef.gridList = mainRef.gridList.splice(0)
			store.dispatch('setPhotGrid', {})
		}
		proxy.$refs.DeviceContentRef.init()
		proxy.$refs.CompoHistoryRef.init(mainRef.gridHistoryList)
		proxy.$loading.close()
		proxy.$toast({
			value: '关闭成功',
			type: 'success'
		})
	} catch (err) {
		proxy.$toast({
			value: '系统错误',
			type: 'error'
		})
	}
}
const getOpenedGridList = async () => {
	for (let grid of deviceManager.photGrids) {
		await deviceManager.closeGrid(grid[0])
	}
}

const changeFigure = (e: any) => {
	proxy.$refs[`FiguresViewRef-${deviceManager.photGridId}`][0].init()
}

onUnmounted(() => {
    getOpenedGridList()
})
</script>